package org.hank.compose_yyzs.ui.screen

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layout
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.MyApp
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.bean.MeasureTaskListBean
import org.hank.compose_yyzs.ui.paging.RefreshList
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.utils.getString
import org.hank.compose_yyzs.utils.getStringGlobal
import org.hank.compose_yyzs.viewmodel.MeasureResultViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/6/5 9:17
 *描述:
 */

@OptIn(ExperimentalFoundationApi::class)
@Destination
@Composable
fun MeasureResultScreen(
    navigation: DestinationsNavigator
) {
    var pagers = listOf(
        getString(resourceId = R.string.measure_all),
        getString(resourceId = R.string.measure_cal_failed),
        getString(resourceId = R.string.measure_cal_succ),
    )

    var viewModel: MeasureResultViewModel = hiltViewModel()
    var pager = viewModel.pager.collectAsLazyPagingItems()

    var pagerState =
        rememberPagerState(initialPage = 0, initialPageOffsetFraction = 0f) { pagers.size }
    var scope = rememberCoroutineScope()
    var state1 = rememberLazyListState()
    var state2 = rememberLazyListState()
    var state3 = rememberLazyListState()

    var refreshing by remember { mutableStateOf(false) }


    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        Surface(shadowElevation = 5.dp) {
            Column(
                modifier = Modifier
                    .background(color = AppTheme.colors.mainColor)
                    .fillMaxWidth()
            ) {
                Text(
                    getString(R.string.measure_title),
                    modifier = Modifier
                        .align(Alignment.CenterHorizontally)
                        .padding(top = 16.dp, bottom = 16.dp)
                    ,
                    style = MaterialTheme.typography.titleLarge
                )
            }
        }
        Spacer(modifier = Modifier.height(4.dp))

        TabRow(selectedTabIndex = pagerState.currentPage, modifier = Modifier.fillMaxWidth()) {
            pagers.forEachIndexed { index, s ->
                Tab(
                    text = {
                        Text(
                            text = s,
                            style = MaterialTheme.typography.bodyLarge.copy(
                                color = AppTheme.colors.textPrimary,
                                fontWeight = FontWeight.Medium
                            )
                        )
                    }, selected = pagerState.currentPage == index, onClick = {
                        scope.launch {
                            pagerState.animateScrollToPage(index)
                        }
                    })
            }
        }

        HorizontalPager(
            state = pagerState,
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .padding(16.dp),
        ) { index ->
            if (pagerState.currentPage == index) {
                RefreshList(
                    lazyPagingItems = pager,
                    isRefreshing = refreshing,
                    onRefresh = {
                        scope.launch {
                            refreshing = true
                            viewModel.refresh()
                            delay(1500)
                            refreshing = false
                        }
                    },
                    listState = if (index == 0) state1 else if (index == 1) state2 else if (index == 2) state3 else state1
                ) {
                    items(
                        pager.itemCount,
                        key = pager.itemKey { it -> it.projectName }) { item ->
                        MeasureItemCompose(pager[item]!!)
                    }
                }
            }
        }

        Surface(shadowElevation = 5.dp) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(AppTheme.colors.mainColor)
                    .padding(8.dp)
                    ,
                horizontalArrangement = Arrangement.SpaceAround
            ) {
                Row {
                    Text(
                        text = String.format(
                            getString(resourceId = R.string.measure_all_point),
                            30
                        )
                    )
                }
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Image(
                        painter = painterResource(id = R.mipmap.ic_success),
                        contentDescription = "",
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = String.format(
                            getString(resourceId = R.string.measure_success),
                            30
                        ),
                        style = MaterialTheme.typography.bodyMedium.copy(
                            color = AppTheme.colors.success
                        )
                    )
                }
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Image(
                        painter = painterResource(id = R.mipmap.ic_fail),
                        contentDescription = ""
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = String.format(
                            getString(
                                resourceId = R.string.measure_failed
                            ), 30
                        ),
                        style = MaterialTheme.typography.bodyMedium.copy(
                            color = AppTheme.colors.error
                        )
                    )
                }
            }
        }

    }
}

@Composable
fun MeasureItemCompose(measureTaskBean: MeasureTaskListBean) {
    Surface(
        shape = MaterialTheme.shapes.small,
        shadowElevation = 0.5.dp
    ) {
        Card {
            Column(
                modifier = Modifier
                    .background(AppTheme.colors.mainColor)
                    .padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 16.dp)
            ) {
                Text(
                    text = measureTaskBean.projectName,
                    style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium)
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = appendNameByMeasureTaskItem(measureTaskBean),
                    style = MaterialTheme.typography.bodyMedium
                )
                Spacer(modifier = Modifier.height(8.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        painter = painterResource(id = R.mipmap.ic_completed),
                        contentDescription = ""
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = measureTaskBean.createdDate,
                        style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary)
                    )
                    Spacer(modifier = Modifier.weight(1f))
                    Text(text = getString(resourceId = R.string.measure_detail_num))
                    Surface(
                        modifier = Modifier.background(AppTheme.colors.background),
                        shape = MaterialTheme.shapes.small
                    ) {
                        Text(
                            text = measureTaskBean.stationNo,
                            style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary)
                        )
                    }
                    Image(
                        painter = painterResource(id = R.mipmap.ic_into_grey),
                        contentDescription = ""
                    )
                }
            }
        }
    }
}

fun appendNameByMeasureTaskItem(item: MeasureTaskListBean): String {
    var subName = ""
    var buildingName =
        if (!item.blockName.isNullOrEmpty()) {
            if (item.blockName.contains("栋"))
                item.blockName
            else
                item.blockName + getStringGlobal(R.string.measure_result_building)
        } else
            ""
    var buildingNumName =
        if (!item.unitName.isNullOrEmpty()) {
            if (!item.unitName!!.contains("单元"))
                (item.unitName + getStringGlobal(R.string.measure_result_building_num))
            else
                item.unitName
        } else
            ""
    var floorName =
        if (!item.floorName.isNullOrEmpty()) {
            if (item.floorName.contains("层"))
                item.floorName
            else
                item.floorName + getStringGlobal(R.string.measure_result_floor)
        } else
            ""
    var roomName =
        if (!item.roomName.isNullOrEmpty())
            if (!item.unitName!!.contains("房"))
                (item.roomName + getStringGlobal(R.string.measure_result_room))
            else
                item.roomName
        else
            ""
    var typeName = if (item.taskType == 1)
        getStringGlobal(R.string.measure_result_type_room)
    else
        getStringGlobal(R.string.measure_result_type_wall)

    var stageName =
        if (item.taskType == 1) {
            MyApp.context.resources.getStringArray(R.array.home_stage)[item.stageType - 1]
        } else {
            MyApp.context.resources.getStringArray(R.array.wall_stage)[item.stageType - 1]
        }
    subName =
        "${buildingName}_${buildingNumName}_${floorName}_${roomName}_${typeName}_${stageName}"
    return subName
}


